package com.sensePlusVR.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Bitmap;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sensePlusVR.base.BaseActivity;
import com.sensePlusVR.bean.CollectionItem;
import com.sensePlusVR.bean.GameItem;
import com.sensePlusVR.db.ImageLibrary;
import com.sensePlusVR.db.ImageLibrary.Callback;
import com.sensePlusVR.main.R;
import com.sensePlusVR.manager.CollectionFollowManager;
import com.sensePlusVR.manager.CommendItemManager;
import com.sensePlusVR.manager.DataCenter;
import com.sensePlusVR.manager.EventListener;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.DialogUtils;
import com.sensePlusVR.utils.DownloadBatchUrl;
import com.sensePlusVR.utils.DownloadTask;
import com.sensePlusVR.utils.EventBusUtils;
import com.sensePlusVR.utils.GameDdNotifyCallback;
import com.sensePlusVR.utils.GameDownload;
import com.sensePlusVR.utils.MyColor;
import com.sensePlusVR.utils.MyDialogUtil;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.MyToast;
import com.sensePlusVR.widget.CircleDLProgressView;
import com.sensePlusVR.widget.dialog.VideoDetailDialog;
import com.sensePlusVR.widget.dialog.VideoPlayDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author: Loren
 * @create: 2016-8-10下午2:54:49
 * @desc: Home --> video adapter
 * 
 */
@SuppressWarnings("unused")
@SuppressLint("UseSparseArrays")
public class CollectionListAdapter extends RecyclerView.Adapter<CollectionListAdapter.ViewHolders>
		implements DownloadBatchUrl.DownloadCallBack{
	private static final String TAG = CollectionListAdapter.class.getSimpleName();
	private Context context;
	private List<GameItem> collectionList;
	private CollectionListAdapter t = this;
	private DataCenter dataCenter;
	//private Map<Integer, CommendItem> commendMap;
	private int fromCollectOrDownload = 0;
	private Map<Integer, ViewHolders> viewHolders; 
	
	//viewHolders
	private final Object viewLock = new Object(); 
	
	//private Object speedUILock = new Object();
	/**
	 * key :scrite,man,sence,woman,anim
	 */
	
	private final String KEY_DOWNLOAD =TAG + "Download";
	private final String KEY_COLLECTION = TAG + "Collection";
	private String KEY = "";
	
	private VideoDetailDialog videoDetailDialog;
	
	//设置
//	public void setCommendMap(Map<Integer, CommendItem> commendMap) {
//		this.commendMap = commendMap;
//	}
	
	EventListener listener = new EventListener() {
		@Override
		public void Notify(int event, Object data, Object Params) {
			// TODO Auto-generated method stub
			if (Params == null || data == null)
				return;
			GameItem gitem = null;
//			if (event == CommendItemManager.EventCommendGot) {
//				gitem = (GameItem) data;
//			} else
				if (event == CommendItemManager.EventCommendChanaged) {
				gitem = (GameItem) data;
			}else{
				return;
			}
//			if(citem == null)return;
//			commendMap.put(citem.getId(), citem);
//			MyLog.d(TAG, "gameId="+citem.getId()+ " commend="+citem.getUp());
			
			ViewHolders holder = null;
			synchronized (viewLock) {

				holder = viewHolders.get(gitem.getId());
			}
			
			if (holder != null && gitem != null && holder.getGameId() == gitem.getId())
				updateCommend(holder, gitem);
		}

	};

	
	private EventListener CFlistener = new EventListener(){

		@Override
		public void Notify(int event, Object data, Object Params) {
			if (event == CollectionFollowManager.EventFollowCollectionGot || Params == null || data == null)
				return;
			
			int resId = (Integer)data;
			MyLog.e(TAG, "event="+event+"  gameId="+resId);
			switch(event){
			case CollectionFollowManager.EventCollectionAdded:
				GameItemUpdate(resId, 1);
				break;
			case CollectionFollowManager.EventCollectionDeled:
				GameItemUpdate(resId, 0);
				break;
			case CollectionFollowManager.EventColloctionedDownload:
				GameItemUpdate(resId, 2);
				break;
			}
		}
		
	};
	
	void GameItemUpdate(final int gameId,final int add){
		
		((BaseActivity) context).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (add == 0){
					for (int location = 0; location < collectionList.size(); location++){
						GameItem item = collectionList.get(location);
						if (item != null){
							if (gameId == item.getId()){
								MyLog.d(TAG, "location  " + location);
								remove(item);
								
								break;
							}
						}
					}
					MyLog.d(TAG, "collectionList size : " + collectionList.size());
				}else if(add == 1){
					if(KEY.equals(KEY_COLLECTION)){
						//GameItem gitem = dataCenter.getGameById(gameId);
						GameItem gitem = GameItem.getGameById(gameId);
						if (gitem == null)
							return;
						boolean isAdd = false;
						if(collectionList.size()== 0){
							isAdd = true;
						}else{
							for(GameItem gameItem : collectionList){
								if(gameItem.getId() != gitem.getId()){
									isAdd = true;
								}else{
									isAdd = false;
									break;
								}
							}
						}
						if(isAdd){
							MyLog.d(TAG, "collectionList add gameId : " + gameId);
							collectionList.add(gitem);
						}
						
//						notifyCommendMap(gitem);
						collecListSort();
					}
				}else if(add == 2){
					collecListSort();
				}
			}
		});
	}
	
	private GameDdNotifyCallback gameDdNotify = new GameDdNotifyCallback() {
		
		@Override
		public void startDownload(Object param) {
			
			MyLog.d(TAG, "startDownload...");
			final GameItem item = (GameItem) param;		
			if (item == null)
				return;
			
			MyLog.d(TAG, "startDownload...gameId : " + item.getId());
			
			ViewHolders tmpholder = null;
			
			synchronized (viewLock) {
				
				tmpholder = viewHolders.get(item.getId());
			}
			
			final ViewHolders holder = tmpholder;
			
			if (holder == null)
				return;
			
			//获取初始下载状态
			final int initProgress = GameDownload.getInitProgress(item);
					
			
			((BaseActivity)context).runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					
					  updateUIDownloadWaiting(holder, initProgress,item);
					
				}
			});
		}
	};
	
	void updateCommend(final ViewHolders holder,final GameItem gameItem) {
//		MyLog.d(TAG,"updateCommend gameItem : " + gameItem);
//		final int gameId =  gameItem.getId();
		((BaseActivity) context).runOnUiThread(new Runnable() {
			@Override
			public void run() {
//					String uped = String.valueOf(gameItem.getPraisecount());
//					int userAction = gameItem.getIsPraise();
//					holder.collection_zan_tv.setText(uped);
//					if (userAction == 0) {
//						holder.collection_zan_iv
//								.setImageResource(R.drawable.favour_collection_selector);
//					} else if (userAction == 1) {
//						holder.collection_zan_iv
//								.setImageResource(R.drawable.favour_collection);
//					}
				//更新列表中Item最新赞信息
				collectionList.set(holder.getMyPosition(),gameItem);
				MyLog.d(TAG, "Mygame commend gameid=" + gameItem.getId());
			}
		});
	}

	@Override
	public void progress(final Object params, final int progress, final int downloadState) {
	
		MyLog.d(TAG,"progress....."+progress+" downloadState="+downloadState);
		
		((BaseActivity) context).runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				
				showToast(downloadState, params, progress);
				
			}
		});
		
	}
	
	
	private void showToast(int downloadState, Object params, final int progress) {

		final GameItem gameItem = (GameItem) params;
		if (gameItem == null)
			return;
		ViewHolders tmpholder = null;

		int holderSize = 0;

		synchronized (viewLock) {

			tmpholder = viewHolders.get(gameItem.getId());

			holderSize = viewHolders.size();
		}

		final ViewHolders holder = tmpholder;

		MyLog.d(TAG, "gameid=" + gameItem.getId() + "holder size:" + holderSize);

		if (holder == null) {
			MyLog.d(TAG, "gameid=" + gameItem.getId()
					+ " has no viewHolder,holder size:" + holderSize);
			// 切换账号后游戏已经下载完再次点击下载秒下，在dettach完后和attach之前回调则导致holder == null,做特殊处理
			if (downloadState == DownloadTask.DownloadSuccess) {
				MyLog.d(TAG, "Download complete");
				// 从收藏列表删除，添加到下载列表
				if (onCollectionDownloadedListener != null) {
					onCollectionDownloadedListener
							.onCollectionDownloaded(gameItem);
				}
			}

			return;
		}

		MyLog.e(TAG, "indentify=" + gameItem.getId() + " progress=" + progress
				+ "downloadState=" + downloadState);

		if (downloadState == DownloadTask.DownloadSuccess) {
			MyLog.d(TAG, "Download complete");
			// 从收藏列表删除，添加到下载列表
			if (onCollectionDownloadedListener != null) {
				onCollectionDownloadedListener.onCollectionDownloaded(holder
						.getGameItem());
			}
			//updateUIDownloading(holder, progress);
		} else if (downloadState == DownloadTask.DownloadFailed) {
			MyToast.showMessage(context,
					context.getString(R.string.download_failed_try_again));
			updateUIDownloadError(holder, progress,gameItem);
		} else if (downloadState == DownloadTask.DownloadCancel) {
			updateUIOnlyFavorite(holder,gameItem);
		} else if (downloadState == DownloadTask.DownloadPause) {
			CollectionItem clcItem = CollectionItem.query(holder.getGameItem()
					.getId());
			if (clcItem != null) {
				updateUIDownloadPause(holder, clcItem.getDownProgress(),gameItem);
			}
		} else if (downloadState == DownloadTask.DownloadDoing) {
			updateUIDownloading(holder, progress,gameItem);
		} else if (downloadState == DownloadTask.DownloadRealDoing) {
			GameDownload.checkOutOfSpace(context, progress, gameItem);
			collecListSort();
		}
	}


	
	public CollectionListAdapter(Context context,List<GameItem> collectionList,int fromCollectOrDownload) {
		this.context = context;
		this.collectionList = collectionList;
		this.fromCollectOrDownload = fromCollectOrDownload;
		viewHolders = new HashMap<Integer, ViewHolders>();
		
		dataCenter = DataCenter.getInstans();
		
		if(fromCollectOrDownload == Constant.FROM_COLLECTION){
			KEY = KEY_COLLECTION;
			
		}else if(fromCollectOrDownload == Constant.FROM_DOWNLOADED){
			KEY = KEY_DOWNLOAD;
		}
	}
	

	@Override
	public ViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
		View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_collection_item, parent, false);
		Log.d(TAG, "onCreateViewHolder view : " + view.toString());
		return new ViewHolders(view);
	}


	private void updateDownloadStatus(final ViewHolders holder, GameItem gameItem){
		//先判断下载状态：如果正在下载则继续显示进度，如果已经下载完成则隐藏下载图标
		if (gameItem != null) {
			 CollectionItem clcItem = CollectionItem.query(gameItem.getId());
			 if(clcItem==null){
				 return;
			 }
			 
			int state = clcItem.getDownloadState();
			
			if(KEY.equals(KEY_DOWNLOAD)){
				
				state = CollectionItem.DownloadFinished;
				
			}
			
			//获取初始下载状态
			final int initProgress = GameDownload.getInitProgress(gameItem);
			 
			MyLog.d(TAG, "updateDownloadStatus initProgress : " + initProgress + " gameId : " + gameItem.getId());
			MyLog.d(TAG, "updateDownloadStatus state : " + state);
			
			if(state==CollectionItem.DownloadError){
				
				updateUIDownloadError(holder,initProgress,gameItem);
				
			}else if (state==CollectionItem.DownloadFinished){
				updateUIDownloadSuccess(holder,gameItem);
			}else if(state==CollectionItem.DownloadNone){
				updateUIOnlyFavorite(holder,gameItem);
				
			}else if(state==CollectionItem.DownloadPause){//暂停状态
				updateUIDownloadPause(holder, clcItem.getDownProgress(),gameItem);
				
			}else if (state==CollectionItem.DownloadDoing){
				MyLog.d(TAG, "updateDownloadStatus isDownloadWaiting : " + GameDownload.isDownloadWaiting(gameItem));
				if(!GameDownload.isDownloadWaiting(gameItem)){
					updateUIDownloading(holder, initProgress,gameItem);
				}else{
					updateUIDownloadWaiting(holder, initProgress,gameItem);
				}
			}
		}
	}
	
	
	@Override
	public void onBindViewHolder(final ViewHolders holder, final int position) {
		EventBusUtils.collectionOnbindViewholder();
		holder.setMyPosition(position);
		final GameItem item = collectionList.get(position);
		holder.setGameItem(item);
		Log.d(TAG, "onBindViewHolder position : " + position);
		Log.d(TAG, "onBindViewHolder item id : " + item.getId());
		holder.setGameId(item.getId());
		holder.itemView.setTag(item);
		holder.collection_split.setVisibility(View.VISIBLE);
		
		if (fromCollectOrDownload == Constant.FROM_DOWNLOADED) {
			if (position == collectionList.size() - 1) {
				holder.collection_split.setVisibility(View.INVISIBLE);
			}
			holder.top.setVisibility(View.VISIBLE);
		}else if(fromCollectOrDownload == Constant.FROM_COLLECTION){
			holder.top.setVisibility(View.GONE);
		}
		holder.collection_name_tv.setText(item.getTitle());
//		CommendItem ci = commendMap.get(item.getId());
//		if (ci != null) {
			String uped = String.valueOf(item.getPraisecount());
			int userAction = item.getIsPraise();
			holder.collection_zan_tv.setText(uped);
			if (userAction == 0) {
				holder.collection_zan_iv.setImageResource(R.drawable.favour_collection_selector);
			} else if (userAction == 1) {
				holder.collection_zan_iv.setImageResource(R.drawable.favour_collection);
			}
//		}
		

		final String imageUrl = item.getImgurl();
		MyLog.d(TAG, "imageUrl :" + imageUrl);
		//默认图片
		holder.collection_cover_default_iv.setVisibility(View.VISIBLE);
		holder.collection_cover_iv.setVisibility(View.INVISIBLE);
		holder.collection_cover_default_iv.setImageResource(R.drawable.loadng_icon);
		ImageLibrary.getInstance().getImageBitmap(context, imageUrl, new Callback() {
				@Override
				public void onImageDownloaded(Bitmap bitmap,String imageUrlCb) {
					MyLog.e(TAG, "bitmap : " + bitmap);
					if (bitmap != null){
						GameItem item = holder.getGameItem();
						String image = item.getImgurl();
						if (image == null)
							return;
						if(image.equals(imageUrlCb)){
							holder.collection_cover_default_iv.setVisibility(View.INVISIBLE);
							holder.collection_cover_iv.setVisibility(View.VISIBLE);
							holder.collection_cover_iv.setImageBitmap(bitmap);
						}
					}
				}
			});
		
		boolean isVRFormat = GameItem.isVRFormat(item);
		boolean is2DFormat = GameItem.is2DFormat(item);
		if(isVRFormat){
			holder.collection_vr_iv.setImageResource(R.drawable.vr_tag_small);
		}else if(is2DFormat){
			holder.collection_vr_iv.setImageResource(R.drawable.nomal_tag_small);
		}
		
		holder.collection_progress.setMaxCount(100);
		holder.collection_progress.setScoreSpSize(10);
		holder.collection_progress.setCircleStrokeWithSp(1.0f);
		holder.collection_progress.setBackCircleColor(context.getResources().getColor(R.color.download_pro_bg));
		//先判断下载状态：如果正在下载则继续显示进度，如果已经下载完成则隐藏下载图标
		updateDownloadStatus(holder, item);
		
		
		holder.collection_fram.setOnClickListener(new MyOnClickListener(holder, position));
		holder.collection_name_linear.setOnClickListener(new MyOnClickListener(holder, position));
		//holder.collection_default.setOnClickListener(new MyOnClickListener(holder, position));
		
		holder.collection_download_linear.setOnClickListener(new MyOnClickListener(holder, position));
		holder.collection_play_linear.setOnClickListener(new MyOnClickListener(holder, position));
		holder.collection_zan_linear.setOnClickListener(new MyOnClickListener(holder, position));
	}

	@Override
	public int getItemCount() {
		return collectionList.size();
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	private OnCollectionDownloadedListener onCollectionDownloadedListener;

	public interface OnCollectionDownloadedListener{
		public void onCollectionDownloaded(GameItem item);
	}
	
	public void setOnCollectionDownloadedListener(OnCollectionDownloadedListener onCollectionDownloadedListener){
		this.onCollectionDownloadedListener = onCollectionDownloadedListener;
	}

	/**
	 * 上传赞或者踩
	 * 
	 * @param item
	 */

	private void uploadCommend(GameItem item) {
		dataCenter.setGameCommend(item.getId());
	}
	
		 
	public class MyOnClickListener implements View.OnClickListener {
		private ViewHolders holder;
		private int position;
		private GameItem gameItem;
//		private CommendItem commendItem;

		public MyOnClickListener(ViewHolders holder, int position) {
			this.holder = holder;
			this.position = position;
//			if (position < collectionList.size())
//				gameItem = collectionList.get(position);
//			if (gameItem != null)
//				commendItem = commendMap.get(gameItem.getId());
		}

		@Override
		public void onClick(View v) {
			MyLog.d(TAG, "click position : " + position);
			MyLog.d(TAG, "gamedownload tasks size : " + GameDownload.getDownloadTaskSize());
			if (position < collectionList.size())
				gameItem = collectionList.get(position);
			//实时更新commendItem
//			if (gameItem != null)
//				commendItem = commendMap.get(gameItem.getId());
			switch (v.getId()) {
			// 详情
			//case R.id.collection_root_linear:
			case R.id.collection_fram:
				
				MyLog.d(TAG, "collection_fram  gameId : " + gameItem.getId());
				
				CollectionItem clcItem = CollectionItem.query(gameItem.getId());
				
				if(clcItem==null){
					
					return;
				}
				
				int state = clcItem.getDownloadState();
				
				MyLog.d(TAG, "collection_fram  state : " + state);
				
				if(state==CollectionItem.DownloadNone||state==CollectionItem.DownloadFinished){//弹出详情
					if(isDismissed){
						jumpVideoDetailDialog();
						}
					return;
				}
				
				if(state==CollectionItem.DownloadDoing){//暂停
					
					MyLog.d(TAG, "CollectionItem.DownloadDoing");
					
					GameDownload.pauseDownload(gameItem);
					
					int progress = GameDownload.getInitProgress(gameItem);
					
					progress = progress>=0?progress:0;
					
					MyLog.d(TAG, "progress pause : " + progress);
					
					//更新UI
					updateUIDownloadPause(holder, progress,gameItem);
					
					
					
				}else if(state==CollectionItem.DownloadPause){//恢复下载
					
					MyLog.d(TAG, "progress resume!");
					
					toDownloadGame(gameItem, holder);
					
					
				}else if(state == CollectionItem.DownloadError){//下载错误
					
					MyLog.d(TAG, "progress error!");
					
					toDownloadGame(gameItem, holder);
					
				}
				collecListSort();
				break;
				
			case R.id.collection_name_linear:
				if(isDismissed){
					jumpVideoDetailDialog();
					}		
				break;
			// 下载
			case R.id.collection_download_linear:
				MyLog.d(TAG, "collection_download_linear");
				CollectionItem clc = CollectionItem.query(gameItem.getId());
				
				if(clc==null){
					return;
				}
				
				int st = clc.getDownloadState();
				
				MyLog.d(TAG, "collection_download_linear st : " + st);
				
				
				if(st==CollectionItem.DownloadPause || st == CollectionItem.DownloadError){
					
					GameDownload.pauseCancelDownload(clc);
					
					updateUIOnlyFavorite(holder,gameItem);
					
				}else if(st==CollectionItem.DownloadDoing){
					
					GameDownload.cancelDownload(gameItem,clc);
					
					updateUIOnlyFavorite(holder,gameItem);
					
				}else if(st==CollectionItem.DownloadNone){//下载
					
					toDownloadGame(gameItem,holder);	
					
				}
				collecListSort();
				break;
			//播放
			case R.id.collection_play_linear:
				MyLog.d(TAG, "collection_play_linear");
				ArrayList<GameItem> gameList = new ArrayList<GameItem>();
				gameList.add(gameItem);
				jumpVideoPlayDialog(gameList);
				break;
			case R.id.collection_zan_linear:
				int userAction = gameItem.getIsPraise();
				if (userAction == 0) {
					uploadCommend(gameItem);
				} else if (userAction == 1) {
					MyToast.showMessage(context, context.getResources().getString(R.string.commended_already));
				}
				break;
			}
		}

		private void jumpVideoDetailDialog() {
//			CommendItem citem = commendMap.get(gameItem.getId());
			videoDetailDialog = new VideoDetailDialog(context, gameItem,
					R.style.FullScreen_Dialog_Tran,true);
			videoDetailDialog.show();
			videoDetailDialog.setOnDismissListener(dismissListener);
			MyDialogUtil.setDialogFullScreenGuide(context, videoDetailDialog);
			isDismissed = false;
		}

		private void jumpVideoPlayDialog(ArrayList<GameItem> gameList) {
			if(isPlayDismissed){
				VideoPlayDialog videoPlayDialog = new VideoPlayDialog(context,gameList);
				videoPlayDialog.show();
				videoPlayDialog.setOnDismissListener(playDismissListener);
				MyDialogUtil.setDialogFullScreen(context, videoPlayDialog);
				isPlayDismissed = false;
				}
		}
	}
	
	private boolean isPlayDismissed = true;
	private OnDismissListener playDismissListener = new OnDismissListener(){
		@Override
		public void onDismiss(DialogInterface dialog) {
			MyLog.d(TAG, "onDismiss...");
			isPlayDismissed = true;
		}
	};
	
	/**
	 * 对收藏列表重新排序
	 */
	private void collecListSort(){
		if (KEY.equals(KEY_DOWNLOAD)){
			notifyDataSetChanged();
			return;
		}
		MyLog.e(TAG, "collectionList count="+collectionList.size());
		GameDownload.sortFavoritesGames(collectionList);
		MyLog.e(TAG, "after sort collectionList count="+collectionList.size());
		notifyDataSetChanged();
	}
	
	private void toDownloadGame(final GameItem gameItem,final ViewHolders holder) {
		//Wifi Mobile 网络提醒
		int networkState = GameDownload.getDownloadStauts();
		String message = null;
		
		if(networkState == GameDownload.GameDownLoadByWifi){
			
			readyGameDownload(gameItem, holder);
			return;
			
		}else if(networkState == GameDownload.GameDownLoadByCelluar){
			
			readyGameDownload(gameItem, holder);
			return;
			
		}else if(networkState == GameDownload.GameDownLoadNotAllowCelluar){
			
			message = context.getString(R.string.wifi_no_cellular_no_collection_dialog_tip);
			
		}else if(networkState == GameDownload.GameDownLoadNoNetwork){
			
			 message = context.getString(R.string.wifi_no_cellular_yes_remain_tip);
			
		}
		
		//如果4G允许则直接下载，不允许则必须打开4G开关才能下载，所以按OK后不做任何操作
		DialogUtils.showConfirmDialogConfirmCancel(context,null, message,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
							
						dialog.dismiss();
					}
				}, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
	}

	private void readyGameDownload(GameItem gameItem,
			final ViewHolders holder) {
		int initProgress = GameDownload.getInitProgress(gameItem);
		
		updateUIDownloadWaiting(holder, initProgress,gameItem);
		
		//CollectionItem.addCollection(gameItem);
		
		GameDownload.downloadGame(gameItem);
	}
	
	private boolean isDismissed = true;
	private OnDismissListener dismissListener = new OnDismissListener(){

		@Override
		public void onDismiss(DialogInterface dialog) {
			MyLog.d(TAG, "onDismiss...");
			isDismissed = true;
		}
	};

	/**
	 * 返回dialog的时候更新列表数据
	 * 
	 * @param position
	 * @param gameItem
	 */
	public void refreshSingle(int position, GameItem gameItem) {
		MyLog.d(TAG, "gameList indexOf: " + this.collectionList.indexOf(gameItem));
		if (gameItem != null) {
			int collectioned = gameItem.getColloctoned();
			if (collectioned == 0) {
				if (position < collectionList.size()) {
					this.collectionList.remove(position);
//					commendMap.remove(gameItem.getId());
				}
				notifyItemChanged(position);
			}
		}
	}

	private GameItem getGameCommends(GameItem gameItem) {
		MyLog.e(TAG, "getcommends, gameId=" + gameItem.getId());
		GameItem gitem = dataCenter.getGameCommend(gameItem.getId());

		return gitem;
	}

	@Override
	public void onViewAttachedToWindow(ViewHolders holder) {
		super.onViewAttachedToWindow(holder);
		
		int hoderSize = 0;
		synchronized (viewLock) {
			
			viewHolders.put(holder.getGameId(), holder);
			
			hoderSize = viewHolders.size();
		}
		
		MyLog.e(TAG, KEY+" onViewAttachedToWindow holderSize="+hoderSize + " gameId : " + holder.getGameId());
	}

	@Override
	public void onViewDetachedFromWindow(ViewHolders holder) {
		super.onViewDetachedFromWindow(holder);
		
		int hoderSize = 0;
		synchronized (viewLock) {
			
			viewHolders.remove(holder.getGameId());
			
			hoderSize = viewHolders.size();
		}
		
		MyLog.e(TAG, KEY+" onViewDetachedFromWindow holderSize="+hoderSize + " gameId : " + holder.getGameId());
	}

	public class ViewHolders extends RecyclerView.ViewHolder {
		public LinearLayout collection_root_linear;
		public FrameLayout collection_fram;
		public ImageView collection_cover_default_iv;
		public ImageView collection_cover_iv;
		public RelativeLayout collection_relative;
		public CircleDLProgressView collection_progress;
		public ImageView collection_vr_iv;
		public LinearLayout collection_name_linear;
		public TextView collection_name_tv;
		public TextView collection_speed_tv;
		public TextView collection_size_tv;
		public LinearLayout collection_zan_linear;
		public RelativeLayout collection_speed_relative;
		public ImageView collection_zan_iv;
		public TextView collection_zan_tv;

		//public LinearLayout collection_default;
		public LinearLayout collection_download_linear;
		public ImageView collection_download_iv;
		public LinearLayout collection_play_linear;
		public View collection_split;
		public TextView top;
		public TextView delete;
		public LinearLayout layout;
		
		public int myPosition;
		public GameItem gameItem;
		public int gameId;
		public boolean isSelect;
		
		public int getMyPosition() {
			return myPosition;
		}

		public void setMyPosition(int myPosition) {
			this.myPosition = myPosition;
		}

		public GameItem getGameItem() {
			return gameItem;
		}

		public void setGameItem(GameItem gameItem) {
			this.gameItem = gameItem;
		}

		public int getGameId() {
			return gameId;
		}

		public void setGameId(int gameId) {
			this.gameId = gameId;
		}
		
		public boolean isSelect() {
			return isSelect;
		}

		public void setSelect(boolean isSelect) {
			this.isSelect = isSelect;
		}
		
		public ViewHolders(View itemView) {
			super(itemView);
			collection_root_linear = (LinearLayout) itemView
					.findViewById(R.id.collection_root_linear);
			collection_fram = (FrameLayout) itemView
					.findViewById(R.id.collection_fram);
			collection_cover_default_iv = (ImageView) itemView
					.findViewById(R.id.collection_cover_default_iv);
			collection_cover_iv = (ImageView) itemView
					.findViewById(R.id.collection_cover_iv);
			collection_relative = (RelativeLayout) itemView
					.findViewById(R.id.collection_relative);
			collection_progress = (CircleDLProgressView) itemView
					.findViewById(R.id.collection_progress);
			collection_vr_iv = (ImageView) itemView
					.findViewById(R.id.collection_vr_iv);
			collection_name_linear = (LinearLayout) itemView
					.findViewById(R.id.collection_name_linear);
			collection_name_tv = (TextView) itemView
					.findViewById(R.id.collection_name_tv);
			collection_speed_tv = (TextView)itemView
					.findViewById(R.id.collection_speed_tv);
			collection_size_tv = (TextView) itemView
					.findViewById(R.id.collection_size_tv);
			collection_zan_linear = (LinearLayout) itemView
					.findViewById(R.id.collection_zan_linear);
			collection_speed_relative = (RelativeLayout)itemView
					.findViewById(R.id.collection_speed_relative);
			collection_zan_iv = (ImageView) itemView
					.findViewById(R.id.collection_zan_iv);
			collection_zan_tv = (TextView) itemView
					.findViewById(R.id.collection_zan_tv);
//			collection_default = (LinearLayout) itemView
//					.findViewById(R.id.collection_default);
			collection_download_linear = (LinearLayout) itemView
					.findViewById(R.id.collection_download_linear);
			collection_download_iv = (ImageView) itemView
					.findViewById(R.id.collection_download_iv);
			collection_play_linear = (LinearLayout) itemView.
					findViewById(R.id.collection_play_linear);
			collection_split = itemView.findViewById(R.id.collection_split);
			
			top = (TextView) itemView.findViewById(R.id.item_top);
			delete = (TextView) itemView.findViewById(R.id.item_delete);
			layout = (LinearLayout) itemView.findViewById(R.id.item_layout);
		}
	}

	/**
	 * 批量更新数据,对分页有下一页情况
	 * 
	 * @param collectionList
	 */
	public void refreshData(List<GameItem> collectionList) {
		this.collectionList = collectionList;
		MyLog.d(TAG, "refreshData...collectionlist size : " + collectionList.size());
		for (int i = 0; i < collectionList.size(); i++) {
			GameItem gameItem = collectionList.get(i);
			MyLog.d(TAG, "refreshData gameItem : " + gameItem.toString());
//			notifyCommendMap(gameItem);
		}
		collecListSort();
	}
	
	public void setCollectionList(List<GameItem> collectionList){
		
		this.collectionList = collectionList;
	}

	// 因为notifyDataSetChanged()不起作用，所以封装此方法模拟刷新
	public void add(GameItem item) {
		MyLog.e(TAG, "add item=" + item.getId());
		collectionList.add(item);
//		notifyCommendMap(item);
		notifyItemInserted(collectionList.size() - 1);
	}

//	private void notifyCommendMap(GameItem item) {
//		CommendItem citem = getGameCommends(item);
//		if (citem == null) {
//			citem = new CommendItem();
//			citem.setId(item.getId());
//		}
//		commendMap.put(item.getId(), citem);
//	}


//	public void move(int position) {
//		MyLog.d(TAG, "mvoe item=" + position);
//		int collectionListSize = collectionList.size();
//		if(position > 0 && position < collectionListSize){
//			GameItem gameItem = collectionList.get(position);
//			collectionList.remove(position);
//			collectionList.add(0, gameItem);
//			notifyItemMoved(position, 0);
//			notifyItemRangeChanged(0, collectionListSize);
//		}
//	}
	
	public void move(GameItem gameItem) {
		MyLog.d(TAG, "mvoe item=" + gameItem);
		int position = collectionList.indexOf(gameItem);
		MyLog.d(TAG, "position : " + position);
		int collectionListSize = collectionList.size();
		if(position > 0 && position < collectionListSize){
			//GameItem gameItem = collectionList.get(position);
			collectionList.remove(position);
			collectionList.add(0, gameItem);
			notifyItemMoved(position, 0);
//			notifyItemRangeChanged(0, collectionListSize);
		}
	}

	public void add(GameItem item, int position) {
		MyLog.d(TAG, "add pos item=" + position);
		collectionList.add(position, item);
//		notifyCommendMap(item);
		notifyItemInserted(position);
	}

	public void remove(GameItem gameItem) {
		MyLog.d(TAG, "remove item=" + gameItem.getId());
		int position = collectionList.indexOf(gameItem);
		if(position == -1)return;
		int preSize = collectionList.size();
		collectionList.remove(position);
//		commendMap.remove(gameItem.getId());
		notifyItemRemoved(position);
		
		//如果删除的是最后一个并且在已经下载 
		if(position==preSize-1&&preSize>1 && fromCollectOrDownload == Constant.FROM_DOWNLOADED){
			
			MyLog.d(TAG, "remove last hoder position="+position+" preSize="+preSize);
					
			//查找删除项的前一个holder
			//先查找GameItem
			GameItem preGameItem = collectionList.get(position-1);
					
			ViewHolders holder = null;
					
			synchronized (viewLock) {
						
				holder = viewHolders.get(preGameItem.getId());
			}
			if(holder!=null){
						
				hideBotomLine(holder);
			}
					
					
		}
		
	}
	

	
	/**
	 * 隐藏底部横线
	 * @param holder
	 */
	private void hideBotomLine(final ViewHolders holder){
		
		((BaseActivity) context).runOnUiThread(new Runnable() {

			@Override
			public void run() {
				
				holder.collection_split.setVisibility(View.INVISIBLE);
				
			}
			
			
		});
		
		
		
	}
	
	
	public void onResume(){
		
		
		dataCenter.addFCEventListener(CFlistener, this, KEY);
		dataCenter.addCommendEventListener(listener, this, KEY);
		
		if(KEY.equals(KEY_COLLECTION)){
			
			//设置回调
			GameDownload.setGameProgressNotify(this,KEY);
			
			GameDownload.setGameDdNotify(gameDdNotify, KEY);
			
		}
		
		
		if(videoDetailDialog != null){
			videoDetailDialog.onResume();
		}
		
		

		
		
		
	}
	
	public void onPause(){
		
		dataCenter.addFCEventListener(null, this, KEY);
		dataCenter.addCommendEventListener(null, this, KEY);
		
		if(KEY.equals(KEY_COLLECTION)){
		
			GameDownload.setGameProgressNotify(null,KEY);
		
			GameDownload.setGameDdNotify(gameDdNotify, KEY);
			
		}
		
		if(videoDetailDialog != null){
			videoDetailDialog.onPause();
		}
		
	}
	
	
	
	/**
	 * 下载暂停状态
	 */
	private void updateUIDownloadPause(ViewHolders holder,int progress,GameItem gameItem){
		MyLog.d(TAG, "updateUIDownloadPause gameId : " + gameItem.getId());
		holder.collection_relative.setVisibility(View.VISIBLE);
		
		holder.collection_download_linear.setVisibility(View.VISIBLE);
		holder.collection_play_linear.setVisibility(View.INVISIBLE);
		
		holder.collection_progress.setCenterWaitImageVisible(false);
		holder.collection_progress.setCenterErrorImageVisible(false);
		holder.collection_progress.setCenterPauseImageVisible(true);
		holder.collection_progress.setScoreVisible(false);
		
		holder.collection_progress.setCurrentCount(progress);
		
		holder.collection_download_iv.setImageResource(R.drawable.download_cancel_selector);
		
		String tipStr = GameDownload.getRatioLengthStr(gameItem);
		setTextVariedColor(tipStr, holder,false);
	}
	
	
	
	/**
	 * 仅仅收藏状态
	 */
	private void updateUIOnlyFavorite(ViewHolders holder,GameItem gameItem){
		holder.collection_relative.setVisibility(View.INVISIBLE);
		
		holder.collection_download_linear.setVisibility(View.VISIBLE);
		holder.collection_play_linear.setVisibility(View.INVISIBLE);
		
		holder.collection_progress.setCenterWaitImageVisible(false);
		holder.collection_progress.setCenterPauseImageVisible(false);
		holder.collection_progress.setCenterErrorImageVisible(false);
		holder.collection_progress.setScoreVisible(false);
		
		holder.collection_download_iv.setImageResource(R.drawable.my_game_download_selector);
		
		String tipStr = GameDownload.getTotalLengthStr(gameItem);
		holder.collection_speed_tv.setText(tipStr);
		holder.collection_size_tv.setText("");
	}
	
	/**
	 * 等待状态
	 */
	private void updateUIDownloadWaiting(ViewHolders holder,int progress,GameItem gameItem){
		
		MyLog.d(TAG,"updateUIDownloadWaiting progress : " + progress);
		holder.collection_relative.setVisibility(View.VISIBLE);
		
		holder.collection_progress.setCenterPauseImageVisible(false);
		holder.collection_progress.setCenterErrorImageVisible(false);
		holder.collection_progress.setCenterWaitImageVisible(true);
		holder.collection_progress.setScoreVisible(false);
		
		holder.collection_progress.setCurrentCount(progress);
		
		holder.collection_download_linear.setVisibility(View.VISIBLE);
		holder.collection_play_linear.setVisibility(View.INVISIBLE);
		
		holder.collection_download_iv.setImageResource(R.drawable.download_cancel_selector);
		
		
		String tipStr = GameDownload.getRatioLengthStr(gameItem);
		setTextVariedColor(tipStr, holder,false);
		
		
	}
	
	/**
	 * 下载状态
	 */
	private void updateUIDownloading(ViewHolders holder,int progress,GameItem gameItem){
			holder.collection_relative.setVisibility(View.VISIBLE);
			
			holder.collection_progress.setCenterPauseImageVisible(false);
			holder.collection_progress.setCenterWaitImageVisible(false);
			holder.collection_progress.setCenterErrorImageVisible(false);
			holder.collection_progress.setScoreVisible(true);
			
			holder.collection_progress.setCurrentCount(progress);
			holder.collection_progress.setScore(progress);
			
			holder.collection_download_linear.setVisibility(View.VISIBLE);
			holder.collection_play_linear.setVisibility(View.INVISIBLE);
			
			holder.collection_download_iv.setImageResource(R.drawable.download_cancel_selector);
			
			String downloadSpeedTip = GameDownload.getRatioLengthStr(gameItem);
			setTextVariedColor(downloadSpeedTip, holder,true);
			
	}
	
	/**
	 * 下载完成
	 */
	private void updateUIDownloadSuccess(ViewHolders holder,GameItem gameItem){
		holder.collection_relative.setVisibility(View.INVISIBLE);
		
		holder.collection_download_linear.setVisibility(View.INVISIBLE);
		holder.collection_play_linear.setVisibility(View.VISIBLE);
		
		holder.collection_progress.setCenterPauseImageVisible(false);
		holder.collection_progress.setCenterWaitImageVisible(false);
		holder.collection_progress.setCenterErrorImageVisible(false);
		holder.collection_progress.setScoreVisible(false);
		
		String tipStr = GameDownload.getTotalLengthStr(gameItem);
		holder.collection_speed_tv.setText(tipStr);
		holder.collection_size_tv.setText("");
		
	}


/**
 * 下载错误
 */
	private void updateUIDownloadError(ViewHolders holder,int progress,GameItem gameItem){
		holder.collection_relative.setVisibility(View.VISIBLE);
		
		holder.collection_download_linear.setVisibility(View.VISIBLE);
		holder.collection_play_linear.setVisibility(View.INVISIBLE);
		
		holder.collection_progress.setCenterWaitImageVisible(false);
		holder.collection_progress.setCenterPauseImageVisible(false);
		holder.collection_progress.setCenterErrorImageVisible(true);
		holder.collection_progress.setScoreVisible(false);
		
		holder.collection_progress.setCurrentCount(progress);
		
		holder.collection_download_iv.setImageResource(R.drawable.download_cancel_selector);
		
		String tipStr = GameDownload.getRatioLengthStr(gameItem);
		setTextVariedColor(tipStr, holder,false);
	}
	
	
	private void setTextVariedColor(String gameSize,ViewHolders holder,boolean isDownloading) {
		String[] strs = gameSize.split("/");
		if (strs.length > 1) {
			String startSize = gameSize;
			if(isDownloading){
				holder.collection_speed_tv.setText(GameDownload.getDownloadSpeedStr());
			}else{
				holder.collection_speed_tv.setText(Constant.SYMBOL_INTHEBAR);
			}
			holder.collection_size_tv.setText(gameSize);
			
			SpannableStringBuilder builder = new SpannableStringBuilder(gameSize);
			ForegroundColorSpan redSpan = new ForegroundColorSpan(MyColor.APP_TEXT_COLOR_GRAY1);
			int startIndex = (gameSize.length() - startSize.length());
			int endIndex = startIndex + strs[0].length();
			builder.setSpan(redSpan, startIndex, endIndex,
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			holder.collection_size_tv.setText(builder);
		}
//		else{
//			if(isDownloading){
//				holder.collection_speed_tv.setText(GameDownload.getDownloadSpeedStr());
//			}else{
//				holder.collection_speed_tv.setText(Constant.SYMBOL_INTHEBAR);
//			}
//			holder.collection_size_tv.setText(gameSize);
//		}
	}
	
}






